package com.wsx.ones.monitor.core.netty;

import com.wsx.ones.monitor.core.exec.pull.PullExecuter;
import com.wsx.ones.monitor.core.exec.pull.PullMessageHandleTask;
import com.wsx.ones.monitor.core.model.RpcRequest;
import com.wsx.ones.monitor.core.model.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 服务端接受数据的处理
 * Created by wangshuaixin on 17/2/7.
 */
public class PullMessageHander extends ChannelInboundHandlerAdapter {

    private ConcurrentHashMap<String, Object> rpcBeanMap;

    public PullMessageHander (ConcurrentHashMap<String, Object> rpcBeanMap) {
        this.rpcBeanMap = rpcBeanMap;
    }

    /**
     * 读取客户端传递的数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RpcRequest rpcRequest = (RpcRequest) msg;

        //初始化返回结果
        RpcResponse rpcResponse = new RpcResponse();

        //将数据设计成线程的形式，保证操作的并发处理
        PullMessageHandleTask handleTask = new PullMessageHandleTask(rpcRequest, rpcResponse, rpcBeanMap);

        //处理客户端传递的数据，并且将处理结果返回给客户端
        PullExecuter.submit(handleTask, rpcRequest, rpcResponse, ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //super.exceptionCaught(ctx, cause);
        ctx.close();
    }
}
